package com.zqq.goods.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import com.zqq.baselibrary.ext.onClick
import com.zqq.baselibrary.ui.activity.BaseActivity
import com.zqq.baselibrary.ui.fragment.BaseMvpFragment
import com.zqq.baselibrary.utils.YuanFenConverter
import com.zqq.baselibrary.widgets.BannerImageLoader
import com.zqq.goods.R
import com.zqq.goods.event.AddCartEvent
import com.zqq.goods.event.GoodsDetailImageEvent
import com.zqq.goods.event.SkuChangedEvent
import com.zqq.goods.event.UpdateCartSizeEvent
import com.zqq.goods.injection.component.DaggerGoodsComponent
import com.zqq.goods.injection.module.GoodsModule
import com.zqq.goods.presenter.GoodsDetailPresenter
import com.zqq.goods.presenter.view.GoodsDetailView
import com.zqq.goods.service.bean.Goods
import com.zqq.goods.ui.activity.GoodsDetailActivity
import com.zqq.goods.widget.GoodsSkuPopView
import com.zqq.provider.router.RouterPath
import kotlinx.android.synthetic.main.fragment_goods_detail_tab_one.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 商品详情Tab One
 * wc
 * @author zqq on 2019/5/30.
 */
class GoodsDetailTabOneFragment : BaseMvpFragment<GoodsDetailPresenter>(), GoodsDetailView {

    private lateinit var mSkuPop: GoodsSkuPopView
    private lateinit var mAnimationStart: Animation //SKU弹层出场动画
    private lateinit var mAnimationEnd: Animation   //SKU弹层退场动画

    private var mCurGoods: Goods? = null  //获取到的商品

    override fun injectComponent() {
        DaggerGoodsComponent.builder()
                .activityComponent(mActivityComponent)
                .goodsModule(GoodsModule())
                .build()
                .inject(this)
        mPresenter.mView = this
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_goods_detail_tab_one, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initAnim()
        initSkuPop()
        loadData()
        initObserve()
    }

    //初始化视图
    private fun initView() {
        mGoodsDetailBanner.setImageLoader(BannerImageLoader())
        mGoodsDetailBanner.setBannerAnimation(Transformer.Accordion)
        mGoodsDetailBanner.setDelayTime(2000)

        //设置指示器位置（当banner模式中有指示器时）
        mGoodsDetailBanner.setIndicatorGravity(BannerConfig.RIGHT)

        //sku弹层
        mSkuView.onClick {
            //第一个参数是当前 跟布局（即Activity的布局然后通过id获取到）
            (activity as GoodsDetailActivity).getRootView()
            //此处是用的另外一个方法
            mSkuPop.showAtLocation((activity as GoodsDetailActivity).contentView,
                    Gravity.BOTTOM and Gravity.CENTER_HORIZONTAL, 0, 0)

            (activity as BaseActivity).contentView.startAnimation(mAnimationStart)

        }

    }

    //初始化缩放动画
    private fun initAnim() {
        mAnimationStart = ScaleAnimation(1f, 0.95f, 1f, 0.95f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        mAnimationStart.duration = 500
        mAnimationStart.fillAfter = true

        mAnimationEnd = ScaleAnimation(0.95f, 1f, 0.95f, 1f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        mAnimationEnd.duration = 500
        mAnimationEnd.fillAfter = true
    }

    //初始化sku弹层
    private fun initSkuPop() {
        mSkuPop = GoodsSkuPopView(activity!!)
        mSkuPop.setOnDismissListener {
            (activity as BaseActivity).contentView
                    .startAnimation(mAnimationEnd)
        }
    }

    //网络-加载数据
    private fun loadData() {
        var goodsId = activity!!.intent!!.getIntExtra(RouterPath.GoodsCenter.KEY_GOODS_ID, -1)
        mPresenter.getGoodsDetailList(goodsId)
    }

    /**
     * 加载SKU数据
     */
    private fun loadPopData(result: Goods) {
        mSkuPop.setGoodsIcon(result.goodsDefaultIcon)
        mSkuPop.setGoodsCode(result.goodsCode)
        mSkuPop.setGoodsPrice(result.goodsDefaultPrice)

        mSkuPop.setSkuData(result.goodsSku)
    }

    /**
     * 监听SKU变化及加入购物车事件
     */
    @SuppressLint("SetTextI18n")
    private fun initObserve() {
        //mSkuPop.registerEventBus(this)

        Bus.observe<SkuChangedEvent>()
                .subscribe { t ->
                    mSkuSelectedTv.text = mSkuPop.getSelectSku() + RouterPath.GoodsCenter.SKU_SEPARATOR + mSkuPop.getSelectCount() + "件"
                }
                .registerInBus(this)

        //监听-到“添加购物车”按钮事件--然后访问网络：添加到购物车
        Bus.observe<AddCartEvent>()
                .subscribe { t ->
                    addCart()
                }
                .registerInBus(this)
    }

    //EventBus接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSkuChangedEvent(event: SkuChangedEvent) {
        mSkuSelectedTv.text = mSkuPop.getSelectSku() + RouterPath.GoodsCenter.SKU_SEPARATOR + mSkuPop.getSelectCount() + "件"
    }

    //EventBus接收消息:监听-到“添加购物车”按钮事件--然后访问网络：添加到购物车
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAddCartEvent(event: AddCartEvent) {
        addCart()
    }

    /**
     * 加入购物车
     */
    private fun addCart() {
        mCurGoods?.let { it ->
            mPresenter.addCart(it.id, it.goodsDesc,
                    it.goodsDefaultIcon, it.goodsDefaultPrice,
                    mSkuPop.getSelectCount(), mSkuPop.getSelectSku())
        }

        //map形式
//        mCurGoods?.let { it ->
//            var map: HashMap<String, Any> = HashMap<String, Any>()
//            map.put("id", it.id)
//            map.put("goodsDesc", it.goodsDesc)
//            map.put("goodsIcon", it.goodsDefaultIcon)
//            map.put("goodsPrice", it.goodsDefaultPrice)
//            map.put("goodsCount", mSkuPop.getSelectCount())
//            map.put("goodsSku", mSkuPop.getSelectSku())
//
//            mPresenter.addCart(map)
//        }
    }

    /**
     * 取消事件监听
     */
    override fun onDestroy() {
        super.onDestroy()
        mSkuPop.unRegistEventBus()
        Bus.unregister(this)
    }


    /***-----------------接口返回---------------------***/
    //获取商品详情 回调
    override fun onGetGoodsDetailResult(result: Goods) {
        mCurGoods = result
        mGoodsDetailBanner.setImages(result.goodsBanner.split(","))
        mGoodsDetailBanner.start()

        mGoodsDescTv.text = result.goodsDesc
        mGoodsPriceTv.text = YuanFenConverter.changeF2YWithUnit(result.goodsDefaultPrice)
        mSkuSelectedTv.text = result.goodsDefaultSku

        //改变FragmentTwo界面
        Bus.send(GoodsDetailImageEvent(result.goodsDetailOne, result.goodsDetailTwo))
//        EventBus.getDefault().post(GoodsDetailImageEvent(result.goodsDetailOne, result.goodsDetailTwo))

        loadPopData(result)
    }

    //加入购物车 回调
    override fun onAddCartResult(result: Int) {
        //更新购物车数量事件
        Bus.send(UpdateCartSizeEvent())
//        EventBus.getDefault().post(UpdateCartSizeEvent())
    }

}